package com.sky.service.user.impl;

import com.alibaba.fastjson.JSON;
import com.sky.constant.JwtClaimsConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.mapper.user.UserMapper;
import com.sky.pojo.User;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.user.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private JwtProperties jwtProperties;


    @Override
    public UserLoginVO login(UserLoginDTO userLoginDTO) {
        String openid = getOpenId(userLoginDTO.getCode());
        User user = userMapper.selectByOpenId(openid);
        if (user == null) {
            user = new User();
            user.setOpenid(openid);
            user.setCreateTime(LocalDateTime.now());
            userMapper.save(user);
        }
        //查到
        HashMap<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.EMP_ID, user.getId());
        //生成token
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);
        //构建返回值
        UserLoginVO userLoginVO = UserLoginVO.builder()
                .openid(openid)
                .token(token)
                .shopName("")
                .shopAddress("")
                .shopTelephone("")
                .shopId(1L)
                .id(user.getId())
                .deliveryFee(null)
                .build();
        return userLoginVO;
    }

    private String getOpenId(String code) {
        if (code == null || code.isEmpty()) {
            throw new RuntimeException("微信登录凭证code不能为空");
        }
        HashMap<String, String> map = new HashMap<>();
        map.put("appid", weChatProperties.getAppid());
        map.put("secret", weChatProperties.getSecret());
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");
        String jsonStr = HttpClientUtil.doGet(WX_LOGIN, map);
        Map res = JSON.parseObject(jsonStr, Map.class);
        return res.get("openid").toString();
    }
}
